<template>
    <div class="danform">
      <el-form :model="form" :label-width="labelWidth" ref="form" style="display:flex;flex-wrap:wrap;">
        <template v-for="(item,key) in form">
        <el-form-item :label="item.label" v-show="formVisible[key].isShow && !item.isHide" :key="key" :style="getFormWidth(item)">
          <!--<el-form-item :label="item.label"  v-if="formVisible[key].isShow" :key="key" :style="width == '960px' && !item.oneLine ? 'width:50%;' : 'width:100%'">-->
          <div slot="label">
            <el-popover v-if="item.popoverText"
              placement="top-start"
              :title="item.popoverTitle ? item.popoverTitle : '提示'"
              :width="item.popoverWidth ? item.popoverWidth : 200"
              trigger="hover"
              :content="item.popoverText">
              <i slot="reference" class="el-icon-warning blue help-btn"></i>
            </el-popover>
            <el-tooltip :tabindex="-1" v-if="item.tooltipText" effect="dark" :content="item.tooltipText" :placement="item.placement ? item.placement : 'top'">
              <i class="el-icon-warning blue help-btn"></i>
            </el-tooltip>
            <span v-if="item.required" style="color:red;">*</span>
            <span>{{item.label}}</span>
          </div>
          <div class="danform-item-content">
          <!--查看内容-->
          <template v-if="item.type == 'look'">
            <div v-if="!item.lookType" class="danform-look">{{item.value}}</div>
            <div v-if="item.lookType == 'cover'" class="danform-look">
              <el-image 
                style="width: 100px; height: 100px;margin-right:10px;margin-bottom:10px;"
                :src="item.value"
                fit="contain"
                :preview-src-list="previewImgList[item.field]">
              </el-image>
            </div>
            <div v-if="item.lookType == 'code'">
              <!--copyable可以复制-->
              <json-viewer
                :value="item.value ? JSON.parse(item.value) : ''"
                :expand-depth=5
                boxed
                sort></json-viewer>
            </div>
            <div v-if="item.lookType == 'pics'" class="danform-look">
              <el-image v-for="imgItem in item.value" :key="imgItem.value"
                style="width: 100px; height: 100px;margin-right:10px;margin-bottom:10px;"
                :src="imgItem"
                fit="contain"
                :preview-src-list="previewImgList[item.field]">
              </el-image>
            </div>
            <el-table v-if="item.lookType == 'table'" :data="item.value" style="width: 100%">
                <el-table-column v-for="tableFieldItem in item.tableField" :key="tableFieldItem.field"
                  :prop="tableFieldItem.field"
                  :label="tableFieldItem.label"
                  :width="tableFieldItem.width ? tableFieldItem.width : ''">
                </el-table-column>
            </el-table>
          </template>
          <!--普通输入框-->
          <el-input v-if="item.type == 'text'" :type="item.type" v-model="item.value" autocomplete="off" :style="{width:item.width ? item.width+'px' : ''}" :disabled="item.readonly ? true : false" :placeholder="item.placeholder" :maxlength="item.maxlength">
            <template slot="append" v-if="item.appendText">{{item.appendText}}</template>
            <template slot="prepend" v-if="item.prependText">{{item.prependText}}</template>
          </el-input>
          <el-input v-if="item.type == 'textSelect'" type="text" v-model="item.value.text" autocomplete="off" :disabled="item.readonly ? true : false" :placeholder="item.placeholder">
            <el-select  :slot="item.slot"  v-model="item.value.select" :disabled="item.readonly ? true : false" :placeholder="item.selectPlaceholder ? item.selectPlaceholder : ''" class="append-select">
              <el-option
                v-for="options in item.options"
                :key="options.value"
                :label="options.label"
                :value="options.value">
              </el-option>
            </el-select>
          </el-input>
          <!--可搜索建议的输入框-->
          <el-autocomplete v-if="item.type == 'autotext'"  class="form-input" clearable v-model="item.value" :fetch-suggestions="(queryString, cb)=>suggestionsSelect(queryString, cb,item.options)" :placeholder="item.placeholder" @select="(e)=>tapAutotextSelect(item.field,e)"></el-autocomplete>
          <!--密码输入框-->
          <el-input v-if="item.type == 'password'" show-password type="password" v-model="item.value" autocomplete="off" :disabled="item.readonly ? true : false" :placeholder="item.placeholder" :maxlength="item.maxlength"></el-input>
          <!--多行输入框-->
          <el-input v-if="item.type == 'textarea'" :placeholder="item.placeholder" type="textarea" :autosize="{ minRows: item.minRows? item.minRows : 2, maxRows: item.maxRows ? item.maxRows : (item.minRows && item.minRows > 4 ? item.minRows : 4)}" :disabled="item.readonly ? true : false" v-model="item.value" autocomplete="off"></el-input>
          <!--数字输入器-->
          <el-input-number v-if="item.type == 'number'" v-model="item.value" :disabled="item.readonly ? true : false" :precision="item.precision ? item.precision : 0" :step="item.step ? item.step : 1" :max="item.max ? item.max : 999999999" :min="item.min ? item.min : 0" :controls="item.controls ? item.controls : true">
            <template slot="append" v-if="item.appendText">{{item.appendText}}</template>
            <template slot="prepend" v-if="item.prependText">{{item.prependText}}</template>
          </el-input-number>
          <!--单价输入器-->
          <el-input-number v-if="item.type == 'price'" @change="(e)=>changePriceInput(item,e)" v-model="item.value" :disabled="item.readonly ? true : false" :precision="item.precision ? item.precision : 2" :step="1" :max="item.max ? item.max : 999999999" :min="item.min ? item.min : 0"></el-input-number>
          <!--日期时间选择器-->
          <el-date-picker  v-if="(item.type=='date' || item.type=='datetime' || item.type=='daterange' || item.type=='datetimerange' || item.type == 'dates')" :disabled="item.readonly ? true : false" :key="item.field" :type="item.type"  v-model="item.value" :placeholder="item.placeholder" class="form-input" clearable></el-date-picker>
          <!--地图地址选择-->
          <template v-if="item.type == 'map'">
            <el-input placeholder="请点击按钮选择地址" v-model="item.value.address">
              <el-button slot="append" icon="el-icon-map-location" @click="openMapPicker(item)"></el-button>
            </el-input>
            <mapGdPicker ref="mapGdPicker" @pickAddress="pickAddress" :field="item.field" :formTypeProp="formTypeProp"></mapGdPicker>
          </template>
          <!--颜色拾取器-->
          <el-color-picker v-if="item.type == 'color'" v-model="item.value"></el-color-picker>
          <!--标签选择器-->
          <template v-if="item.type == 'tagcolor'">
            <div class="tagcolor-value" @click="openTagColorPicker(item)" :style="{color:item.value.color_text? item.value.color_text:'#333',background:item.value.color_bg ? item.value.color_bg:'#FFF','border-color':item.value.color_border ? item.value.color_border:'#333'}">点这里修改颜色</div>
            <dialogTagColorPicker ref="tagColorPicker" @pickTagColor="pickTagColor" :field="item.field" :formTypeProp="formTypeProp"></dialogTagColorPicker>
          </template>
          <!--树形单选,修改时因为获取数据和获取选项异步，暂时没法设置默认选中，不适合修改使用-->
          <el-tree v-if="item.type == 'treeSelect'" 
            :ref="item.field"
            show-checkbox 
            :data="item.options" 
            :highlight-current="true" 
            :default-expand-all="item.defaultExpandAll ? item.defaultExpandAll :true" 
            :props="{label:item.labelField ?item.labelField : 'label'}"
            :node-key="item.valueField ? item.valueField : 'id'"></el-tree>
          <!--树形单选,修改时因为获取数据和获取选项异步，暂时没法设置默认选中，不适合修改使用-->
          <el-tree v-if="item.type == 'treeRadio'" :ref="item.field" :data="item.options" @node-click="(e)=>tapTreeRadioNode(item.field,e)" :highlight-current="true" :default-expand-all="true" node-key="id"></el-tree>
          <!--多选-->
          <template v-if="item.type == 'checkbox'">
            <el-checkbox v-if="item.options && item.options.length > 0" :indeterminate="item.isIndeterminate" v-model="item.isCheckAll" @change="(e)=>changeCheckboxAll(item,e)">全选</el-checkbox>
            <el-checkbox-group v-model="item.value" @change="(e)=>changeCheckboxGroup(item,e)">
              <el-checkbox v-for="checkboxItem in item.options" :label="checkboxItem.value" :key="checkboxItem.value">{{checkboxItem.label}}</el-checkbox>
            </el-checkbox-group>
          </template>
      
          <!--自定义标签-->
          <tagsEditor v-if="item.type == 'tags'" :value.sync="item.value" :limit="item.limit" :isUseTemp="item.tempOptions ? true : false"  @tapTemp="tapTemp(item.field)" ref="tags"></tagsEditor>
          <!--开关样式-->
          <el-switch v-if="item.type =='switch'" v-model="item.value" :active-value="item.activeValue ? item.activeValue : 1" :inactive-value="item.inactiveValue || item.inactiveValue === false ? item.inactiveValue : 0"  :active-text="item.activeText ? item.activeText : ''" :inactive-text="item.inactiveText ? item.inactiveText : ''"></el-switch>
          <!--单选,按钮样式-->
          <el-radio-group v-if="item.type =='radio' && item.radioType=='button'" v-model="item.value" :size="item.size ? item.size: 'medium'">
            <el-radio-button v-for="radioItem in item.options" :key="item.field + radioItem.value"  :label="radioItem.value">{{radioItem.label}}</el-radio-button>
          </el-radio-group>
          <!--单选,普通样式-->
          <el-radio-group  v-if="item.type =='radio' && item.radioType != 'button' " v-model="item.value">
            <el-radio v-for="radioItem in item.options" :border="item.radioType == 'border' ? true : false" :key="item.field + radioItem.value" :label="radioItem.value">{{radioItem.label}}</el-radio>
          </el-radio-group >
          <!--级联下拉选择-->
          <el-cascader v-if="item.type =='cascaderRadio'" 
          v-model="item.value" :options="item.options" 
          :props="{ 
            checkStrictly: item.checkStrictly ? true : false,
            multiple : item.multiple ? true : false,
            label:item.optionsLabelField ? item.optionsLabelField : 'label',
            value:item.optionsValueField ? item.optionsValueField : 'value'
          }" class="form-input" :show-all-levels="item.showLast ? false : true" filterable clearable></el-cascader>
          <!--固定数据下拉选择框-->
          <el-select v-if="item.type=='select' && !item.unionType"  v-model="item.value" :placeholder="item.placeholder" :disabled="item.readonly ? true : false" class="form-input" clearable :filterable="item.filterable? true :false ">
            <el-option
              v-for="options in item.options"
              :key="options.value"
              :label="options.label"
              :value="options.value">
            </el-option>
          </el-select>
          <!--读取数据下拉选择框-->
            <el-select v-if="item.type=='selectdata'" :multiple="item.multiple ? true : false" v-model="item.value" :placeholder="item.placeholder" :filterable="item.filterable === false ? false : true" :disabled="item.readonly ? true : false" class="form-input" clearable>
               <template v-for="group in item.options">
                <el-option-group
                  v-if="item.children && item.children.length > 0"
                  :key="group.value"
                  :label="group.label">
                    <el-option
                      v-for="item in group.children"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-option-group>
                  <el-option
                    v-else
                    :key="item.optionsValueField ? group[item.optionsValueField] : group.value"
                    :label="item.optionsLabelField ? group[item.optionsLabelField] : group.label"
                    :value="item.optionsValueField ? group[item.optionsValueField] : group.value">
                  </el-option>
                </template>
            </el-select>
          <!--弹出表格数据列表选择框-->
          <template v-if="item.type == 'combobox'">
            <el-select
              v-model="item.value" :placeholder="item.placeholder" :filterable="true" :disabled="item.readonly ? true : false" class="combobox-input" clearable
              remote
              reserve-keyword
              :remote-method="(e)=>remoteMethod(item,e)"
              :loading="item.comboboxLoading">
              <el-option
                v-for="group in item.options"
                :key="item.optionsValueField ? group[item.optionsValueField] : group.value"
                :label="item.optionsLabelField ? group[item.optionsLabelField] : group.label"
                :value="item.optionsValueField ? group[item.optionsValueField] : group.value">
                  <span style="float: left">{{ item.optionsLabelField ? group[item.optionsLabelField] : group.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.optionsRemarkField ? group[item.optionsRemarkField] : group.remark }}</span>
              </el-option>
            </el-select>
            <el-button icon="el-icon-notebook-2" class="combobox-btn" @click="openDataPicker(item)"></el-button>
            <dialogDataPicker ref="dataPicker" @pickData="pickData" :field="item.field" :title="'选择'+item.label" :getPageAction="item.dataController" :gridName="item.gridName" :formTypeProp="formTypeProp"></dialogDataPicker>
          </template>
          <!--单张封面图片选择-->
          <template v-if="item.type == 'cover'">
            <el-upload
              class="cover-uploader"
              name="uploadFileData"
              :data="uploadPlatformData"
              :action="uploadImgUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="(e)=>uploadCoverSuccess(e,key)">
                <img v-if="item.value" :src="item.value" class="cover">
                <i v-else class="el-icon-plus cover-uploader-icon"></i>
            </el-upload>
          </template>
          <!--多张图片可拖拽-->
          <uploadImageDrag v-if="item.type == 'pics'" :value.sync="item.value" :isShowCover="item.isShowCover" ref="uploadImageDrag"></uploadImageDrag>
          <!--图片链接-->
          <uploadImageHyperlink v-if="item.type == 'hyperlink'" :value.sync="item.value" ref="uploadImageHyperlink"></uploadImageHyperlink>
          <!--属性添加器-->
          <attrEditor v-if="item.type == 'attr'" :value.sync="item.value" @updateAttrData="updateAttrData" :field="item.field"  :options="item.options" :ref="item.field"></attrEditor>
          <!--文件上传-->
          <el-upload
            v-if="item.type=='file'"
            class="upload-file"
            name="uploadFileData"
            :action="uploadFileUrl"
            :data="uploadPlatformData"
            :limit="item.limit ? item.limit : 99"
            :on-remove="(e)=>uploadFileRemove(e,key)"
            :headers="uploadHeaders"
            :file-list="item.value"
            :on-exceed="(e)=>uploadFileExceed(e,key)"
            :on-change="(e)=>uploadFileChange(e,key)"
            :on-success="(e)=>uploadFileSuccess(e,key)">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不超过2Mb</div>
          </el-upload>
          <!--富文本编辑-->
          <div v-if="item.type == 'richtext'"><tinymce v-model="item.value" :height="300" /></div>
          <!--可编辑表格列表-->
          <tableEditor v-if="item.type == 'tableEditor'" :ref="item.field" :tableField="item.tableField" :showTemp="item.tempOptions ? true : false" @tapTemp="tapTemp(item.field)"></tableEditor>
          <span v-if="item.afterText" style="padding-left:5px;">{{item.afterText}}</span>
        </div>
        <div class="dan-form-item-intro" v-if="item.introText" v-html="item.introText"></div>
        </el-form-item>
        </template>
        <slot name="user"></slot>
      </el-form>
    </div>
</template>
<style scoped>
.danform{padding:20px 25px 5px 10px;}
.help-btn{cursor:help;margin-right:2px;}
.form-input{width:300px;}
.combobox-input{width:230px;}
.combobox-btn{position:relative;left:-1px;top:-1px;width:60px;}
.append-select{width:80px;}
.tagcolor-value{border:1px solid #ccc;display: flex;justify-content: center;align-items: center;border-radius: 4px;margin-bottom:10px;height:32px;padding:0 20px;cursor:pointer;}
.dan-form-item-intro{color:#969799;font-size:12px;line-height:18px;padding-top:5px;}
</style>
<script>
import {checkCondition} from '@/utils';
import {getTime,date} from '@/utils';
import {getSelectData,getTreeData,getComboboxData } from '@/api/common.js';
import Tinymce from '@/components/Tinymce';
import uploadImageDrag from '@/components/common/uploadImageDrag';
import uploadImageHyperlink from '@/components/common/uploadImageHyperlink';
import attrEditor from './attrEditor';
import mapGdPicker from './mapGdPicker';
import dialogDataPicker from 'common/dialogDataPicker';
import dialogTagColorPicker from 'common/dialogTagColorPicker';
import tagsEditor from './tagsEditor';
export default {
  components:{Tinymce,attrEditor,uploadImageDrag,uploadImageHyperlink,mapGdPicker,dialogDataPicker,dialogTagColorPicker,tagsEditor},
  props:{
    labelWidth:{
      type:String,
      default(){
        return '100px';
      }
    },
    formTypeProp:{
      type:String,
      default(){
        return 'add';
      }
    },
    formSize:{
      type:String,
      default(){
        return '';
      }
    },
    formData:{
      type:Object,
      default(){
        return {};
      }
    },
    formWidth:{
      type:String,
      default(){
        return '500px';
      }
    }
  },
  data(){
    return {
      id:0,
      isShowDialog:false,
      form:{},
      uploadImgUrl:this.$config.requestUrl+'/' + this.$config.app+'/' + this.$config.version + '/Upload/uploadImage',
      uploadFileUrl:this.$config.requestUrl+'/' + this.$config.app+'/' + this.$config.version + '/Upload/uploadFile',
      uploadHeaders:this.$store.getters.userInfo.user_token ? {'User-Token' :this.$store.getters.userInfo.user_token} : {},
      uploadPlatformData:{
        platform_app_id:this.$store.getters.appInfo.platform_app_id,
        platform_user_id:this.$store.getters.appInfo.platform_user_id,
        platform_app_user_id:this.$store.getters.appInfo.platform_app_user_id
      },
      activeTabName:'',
      previewImgList:{},
      width:'',
      test:'',
      callBacks:{}
    }
  },
  created(){
    
  },
  mounted(){

  },
  methods:{
    initForm(){
      this.width = this.formWidth;
      this.callBacks = {};
      //获取表单
      let form = {...this.formData};
      //初始化表单
      for (let k in form) {
        //处理必填验证显示
        if(form[k].rule){
          if (form[k].rule == 'require') {
            form[k].required = true;
          } else {
            for (let i=0;i < form[k].rule.length; i++){
              if (form[k].rule[i] == 'require') {
                form[k].required = true;
                break;
              }
            }
          }
        }
        if (form[k].type == 'pics' || form[k].type == 'hyperlink'){
          //多选图片初始化
          form[k].value =  [];
        } else if (form[k].type == 'file') {
          form[k].value =  [];
        } else if (form[k].type == 'attr') {
          form[k].value =  [];
        } else if (form[k].type == 'map') {
          form[k].value = {address:'',lng_gd:'',lat_gd:''}
        } else if (form[k].type == 'textSelect') {
          form[k].value = {text:form[k].defaultTextValue ? form[k].defaultTextValue : '',select:form[k].defaultSelectValue ? form[k].defaultSelectValue : ''};
        } else if (form[k].type == 'tags') {
          form[k].value =  [];
        } else if (form[k].type == 'look' && form[k].lookType == 'table') {
          form[k].value =  [];
        } else {
          //如果有默认值，设置默认
          if (form[k].default || form[k].default == '0') {
            if (form[k].type == 'datetime' && form[k].default =='nowTime'){
              //如果是默认当前时间
              form[k].value = new Date(new Date().toDateString());
            } else {
              //设置其他默认值
              form[k].value = form[k].default;
            }
          } else {
            //无默认值则为空字符
            form[k].value = '';
          }
        }
        //设置预设选项(PS：需要同步修改tableEditor)
        if (form[k].optionsType == 'sex') {
          form[k].options = [{label:'男',value:1},{label:'女',value:2}];
        } else if (form[k].optionsType == 'education'){
          form[k].options = [{label:'小学',value:'小学'},{label:'初中',value:'初中'},{label:'高中',value:'高中'},{label:'大专',value:'大专'},{label:'本科',value:'本科'},{label:'硕士',value:'硕士'},{label:'博士及以上',value:'博士及以上'}]
        } else if (form[k].optionsType == 'relation'){
          form[k].options = [{label:'父母',value:'父母'},{label:'子女',value:'子女'},{label:'配偶',value:'配偶'},{label:'兄弟姐妹',value:'兄弟姐妹'},{label:'同事',value:'同事'},{label:'其他',value:'其他'}];
        } else if (form[k].optionsType == 'marital'){
          form[k].options = [{label:'未婚',value:'未婚'},{label:'已婚',value:'已婚'},{label:'离婚',value:'离婚'},{label:'再婚',value:'再婚'},{label:'丧偶',value:'丧偶'}];
        } else if (form[k].optionsType == 'reward'){
          form[k].options = [{value:1,label:'积分'},{value:2,label:'钱包余额'},{value:8,label:'普通商品'}];
        } else if (form[k].optionsType == 'deliver'){
          form[k].options = [{value:1,label:'无需配送'},{value:2,label:'物流快递'}];
        }
        //如果是选择数据，获取选择列表
        if (form[k].type == 'selectdata' || (form[k].type == 'checkbox' && form[k].dataController)){
          this.getSelectData(form[k]);
        }
        if (form[k].type == 'checkbox' ){
          form[k].value = [];
          //这里加了if，因为如果不加，在配合隐藏条件的情况下，会无法正常切换状态，原因未知
          if (form[k].isCheckAll) form[k].isCheckAll = false;
          if (form[k].isIndeterminate) form[k].isIndeterminate = false;
          if (form[k].dataController) {
              this.getSelectData(form[k]).then(()=>{
                this.initCheckbox(k);
              });
          } else {
            this.initCheckbox(k);
          }

        }
        if (form[k].type == 'treeRadio'){
          this.getTreeData(form[k]);
        }
        if (form[k].type == 'treeSelect'){
          this.getTreeData(form[k]);
        }
        if (form[k].type == 'cascaderRadio'){
          this.getCascaderData(form[k]);
        }
        
        
      }
      //获取表单
      this.form = form;
      //需要调用组件的放在表单渲染后再执行，不然没表单，没加载，ref找不到
      this.$nextTick(()=>{
        for (let k in form) {
          if (form[k].type == 'tableEditor') {
            this.$refs[k][0].init();
          } else if (form[k].type == 'attr') {
            this.$refs[k][0].init();
          }
        }
      });
    },
    updateFieldValue(field,value){
      if (this.form[field].type == 'tableEditor'){
        this.$refs[field][0].updateForm(value);
      } else {
        this.$set(this.form[field],'value',value);
      }
    },
    updateForm(data){
      //更新表单值
      for (let k in this.form) {
        if (data[k] || data[k] == '0') {
          if (this.form[k].type == 'richtext') {
            //Todo:目前如果打开有报错的话，就再也出不来内容了，待修正
            let tinymces = window.tinymce ? window.tinymce.get() : [];
            if (tinymces.length > 0) tinymces[0].setContent(data[k]);
          } else if (this.form[k].type == 'datetime' && this.form[k].rule == 'timeToStamp'){
            //let field = k.substring(0,k.length - 5) + 'time';
            //this.$set(this.form[k],'value',data[field] ? data[field] : '');
            //2021/11/13又改了，不确定是否影响以前的东西
            console.log(data,k,data[k]);
            this.$set(this.form[k],'value',data[k] ? date(data[k]) : ''); 
          } else if (this.form[k].type == 'tableEditor') {
            this.$refs[k][0].updateForm(data[k]);
          } else if (this.form[k].type == 'map'){
            let obj = {};
            obj[this.form[k].field] = data[k];
            obj['lng_gd'] = data[this.form[k].lng];
            obj['lat_gd'] = data[this.form[k].lat];
            this.$set(this.form[k],'value',obj);
          } else if (this.form[k].type == 'combobox') {
            if (data[k] == '0') {
              this.$set(this.form[k],'value','');
            } else {
              this.$set(this.form[k],'options',[{label:data[k+'_combobox_label'],value:data[k]}]);
            }
          } else if (this.form[k].type == 'selectdata'){
            if (data[k] == '0') {
              this.$set(this.form[k],'value','');
            } else {
              this.$set(this.form[k],'value',data[k]);
            }
          } else if (this.form[k].type == 'look') {
            this.$set(this.form[k],'value',data[k]);
            if (this.form[k].lookType == 'pics'){
              this.previewImgList[this.form[k].field] = data[k];
            } else if (this.form[k].lookType == 'cover') {
              this.previewImgList[this.form[k].field] = [data[k]];
            }
          } else if (this.form[k].type == 'treeSelect'){
            if (data[k] && !this.form[k].optionsComplete) {
              this.$refs[k][0].setCheckedKeys(data[k]);
              this.form[k].optionsComplete = true;
            }
          } else if (this.form[k].type == 'checkbox'){
            this.$set(this.form[k],'value',data[k]);
            this.initCheckbox(k);
          } else {
            this.$set(this.form[k],'value',data[k]);
          }
          //如果值是k字段的写上面，因为会判断value，不存在不处理，如果不是写下面
        } else if (this.form[k].type == 'textSelect'){
          this.$set(this.form[k],'value',{text:data[this.form[k].textField] ? data[this.form[k].textField] :'',select:data[this.form[k].selectField] ? data[this.form[k].selectField] : ''});
        } else if (this.form[k].type == 'pics') {
          this.$set(this.form[k],'value',[]);
        } else if (this.form[k].type == 'hyperlink') {
          this.$set(this.form[k],'value',[]);
        } else if (this.form[k].type == 'attr'){
          this.$set(this.form[k],'value',data[k+'_kind']);
          this.$set(this.form[k],'attrData',data[k+'_data']);
          //this.$nextTick(()=>{
            this.$refs[k][0].setAttrData(data[k+'_data']);
          //})
        } 
      }
    },
    getSelectData(item){
      //获取下拉选择数据的数据源
      return new Promise(resolve =>{
         if (item.dataController) {
          getSelectData(item.dataController).then(data=>{
            this.$set(this.form[item.field],'options',data);
            resolve();
          });
        }
      })
     
    },
    getTreeData(item){
      //获取下拉选择数据的数据
      if (item.dataController) {
        getTreeData(item.dataController,1).then(data=>{
          this.$set(this.form[item.field],'options',data);
          if (item.type == 'treeSelect' || item.type == 'treeRadio') {
              this.$nextTick(()=>{
                if (item.value && !item.optionsComplete) {
                  this.$refs[item.field][0].setCheckedKeys(item.value);
                  item.optionsComplete = true;
                }
            })
          }
        });
      }
    },
    getCascaderData(item){
      //获取下拉选择数据的数据
      if (item.dataController) {
        getTreeData(item.dataController).then(data=>{
          this.$set(this.form[item.field],'options',data);
        });
      }
    },
    setSelectOptions(field,data){
      this.$set(this.form[field],'options',data);
    },
    tapTreeRadioNode(field,e){
      this.$set(this.form[field],'value',e.value);
    },
    tapAutotextSelect(field,e){
      this.$set(this.form[field],'value',e.value);
    },
    suggestionsSelect(queryString, cb,options){
      var restaurants = options;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    getFormData(){
      for (let k in this.form){
        if (this.form[k].type == 'tableEditor') {
          this.form[k].value = this.$refs[this.form[k].field][0].getFormData();
        }
      }
      return this.form;
    },
    updateAttrData(field,result){
      this.form[field].attrData = result;
    },
    uploadCoverSuccess(e,key){
      this.form[key].value = e.data.url;
    },
    uploadFileSuccess(e,key){
      this.form[key].value.push({name:e.data.original_name,url:e.data.url});
     
    }, 
    uploadFileChange(file,fileList,key){
      
    },
    uploadFileExceed(fileList,key){
      if (this.form[key].limit == 1) {
        this.$tool.errorToast('请先删除原文件“'+this.form[key].value[0].name+'”再上传');
      } else {
        this.$tool.errorToast('最多只能上传'+this.form[key].limit +'个文件')
      }
    },
    uploadFileRemove(e,key){
      let arr = [];
      this.form[key].value.forEach(item=>{
        if (item.status == 'success' && item.uid != e.uid)  arr.push(item);
      });
      this.form[key].value = arr;
    },
    remoteMethod(item,query) {
      if (query.trim() !== '') {
        this.$set(this.form[item.field],'comboboxLoading',true);
        setTimeout(() => {
          getComboboxData(item.dataController,query.trim()).then(data=>{
            this.$set(this.form[item.field],'comboboxLoading',false);
            this.$set(this.form[item.field],'options',data);
          })
          
        }, 200);
      } else {
        item.options = [];
      }
    },
    openDataPicker(item){
      this.$refs.dataPicker[0].open(item.field,item.value);
    },
    pickData(field,data){

    },
    openMapPicker(item){
      this.$refs.mapGdPicker[0].open(item.field,item.value);
    },
    openTagColorPicker(item){
      this.$refs.tagColorPicker[0].open(item.field,item.value);
    },
    pickTagColor(field,result){
      this.form[field].value = {};
      this.$set(this.form[field],'value',result);
    },
    pickAddress(field,addr){
      this.form[field].value = {};
      this.$set(this.form[field],'value',addr);
    },
    getFormWidth(item){
      if (item.oneLine) return 'width:100%';
      if (this.formSize == 'big') return 'width:33.3%';
      if (this.formSize == 'small') return 'width:100%';
      return 'width:50%';
    },
    changePriceInput(item,oldVal,newVal){

    },
    tapTemp(field){
      this.$emit('tapTemp',field);
    },
    jsonParse(v){
      return JSON.stringify(JSON.parse(v));
    },
    submit(){

    },
    //checkbox部分
    changeCheckboxGroup(item,val){
      let checkedCount = item.value.length;
      this.$set(item,'isCheckAll',checkedCount === item.options.length)
      this.$set(item,'isIndeterminate',checkedCount > 0 && checkedCount < item.options.length)
    },
    changeCheckboxAll(item,val){
      if (!item.isCheckAll && !item.isIndeterminate) {
        this.$set(item,'value',[]);
        this.$set(item,'isCheckAll',false)
        this.$set(item,'isIndeterminate',false)
      } else if (item.isCheckAll || item.isIndeterminate){
        let arr = [];
        item.options.forEach(checkItem=>{
          arr.push(checkItem.value);
        });
        this.$set(item,'value',arr);
        this.$set(item,'isCheckAll',true)
        this.$set(item,'isIndeterminate',false)
      }
    },
    initCheckbox(k){
      //解决获取数据列表和赋值的异步问题
      if (this.callBacks[k + '_checkbox']) {
        if (this.callBacks[k + '_checkbox'] >= 1) {
          let checkedCount = this.form[k].value.length;
          this.$set(this.form[k],'isCheckAll',checkedCount === this.form[k].options.length)
          this.$set(this.form[k],'isIndeterminate',checkedCount > 0 && checkedCount < this.form[k].options.length)
        }
      } else {
        this.callBacks[k + '_checkbox'] = 1;
      }
      this.form[k]
    }

  },
  watch:{

  },
  computed:{
    formVisible(){
      //复制表单
      let form = {};
      //遍历表单
      for (let k in this.form){
        //默认全显示
        form[k] = {field:k};
        form[k].isShow = true;
        if (this.form[k].condition){
          form[k].isShow = checkCondition(this.form,this.form[k].condition) ? true : false;
        } else if (this.form[k].conditionArr) {
          let isShow = true;
          this.form[k].conditionArr.forEach(condiItem=>{
            if (!checkCondition(this.form,condiItem)) isShow = false;
          })
          form[k].isShow = isShow;
        } else {
          continue;
        }
        //判断是否存在显示条件
        
        /*if (this.form[k].condition) {
          //有条件
          if (this.form[k].condition.length = 2) {
            //条件参数2个为等于
            if (this.form[this.form[k].condition[0]].value == this.form[k].condition[1]){
              form[k].isShow = true;
            } else {
              form[k].isShow = false;
            }
          }
        }*/
      }
      return form;
    }
  }
}


</script>